<template>
    <view @touchmove="cancelFocus" class="diy-form-input dir-top-nowrap" :style="cRadioStyle">
        <view v-if="mode != 'text'" class="diy-form-label" :class="data.style == 3 ? mode == 'position' ? 'inline cross-top' : 'inline cross-center' : ''" :style="cTitleStyle">
            <view>
                <view>{{data.title}}</view>
                <text v-if="data.is_required == '1' && data.title">*</text>
            </view>
        </view>
        <view class="input-item" :style="itemStyle">
            <view v-if="mode == 'text'" class="diy-form-label" :style="cTitleStyle">
                <view>
                    <view>{{data.title}}</view>
                    <text v-if="data.is_required == '1' && data.title">*</text>
                </view>
            </view>
            <view v-if="mode == 'text'" :style="data.style == 2 ? inputItemStyle : ''">
                <textarea class="input" :disabled="data.is_disabled == 1 ? true: false" :placeholder="data.placeholder" :placeholder-style="placeholderStyle" :maxlength="max" v-model="text" auto-height type="text" :show-count="hiddenCount"  @input="textInput" :style="inputStyle" />
            </view>
            <view v-else-if="mode == 'position'" class="input position"  @click.stop="getChooseLocation" :style="inputStyle">{{text ? text : data.placeholder}}
                <image class="position-icon" src="/static/image/icon/diy-position.png"></image>
            </view>
            <input v-else-if="inputType === 'number'" type="number" @click.stop="getChooseLocation" class="input" :disabled="data.is_disabled == 1 ? true: false" :placeholder="data.placeholder" :placeholder-style="placeholderStyle" :maxlength="max" v-model="text" @focus="getIndex" @blur="cancelIndex" :style="inputStyle" />
            <input v-else-if="inputType === 'idcard'" type="idcard" @click.stop="getChooseLocation" class="input" :disabled="data.is_disabled == 1 ? true: false" :placeholder="data.placeholder" :placeholder-style="placeholderStyle" :maxlength="max" v-model="text" @focus="getIndex" @blur="cancelIndex" :style="inputStyle" />
            <input v-else-if="inputType === 'text'"  type="text" @click.stop="getChooseLocation" class="input" :disabled="data.is_disabled == 1 ? true: false" :placeholder="data.placeholder" :placeholder-style="placeholderStyle" :maxlength="max" v-model="text" @focus="getIndex" @blur="cancelIndex" :style="inputStyle" />
            <view v-if="text && mode == 'text'" class="count-num" :class="data.style == 1 ? 'bottom' : ''" :style="{'background-color' : data.style == 1 ? data.bg_color : data.fill_color,'color': data.placeholder_color}">{{number}}/{{data.max}}</view>
        </view>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    export default {
        name: 'diy-form-input',
        data() {
            return {
                text: '',
                max: 300,
                hiddenCount: false,
                number: 0,
                data: {
                    is_required: '0',
                    title: '',
                    placeholder: '',
                    default: '',
                    allow: ['1','2','3','4'],
                    mode: 1,
                    style: 1,
                    is_disabled: 0,
                    min: 0,
                    max: 300,
                    inputPadding: 0,
                    radius: 10,
                    title_color: '#545B60',
                    placeholder_color: '#BEC3C7',
                    text_color: '#242424',
                    border_color: '#E5E7EC',
                    fill_color: '#FFFFFF',
                    bg_color: '#FFFFFF'
                }
            }
        },
        props: {
            index: [Number, String],
            mode: {
                type: String,
                default: 'input'
            },
            value: {
                type: Object
            }
        },
        computed: {
            inputType() {
                if(this.data.mode == 1 && this.mode == 'input' && this.data.allow && this.data.allow[0] == 'number' && this.data.allow.length == 1) {
                    return 'number';
                }else if(this.data.mode == 2) {
                    return 'number';
                }else if(this.data.mode == 4) {
                    return 'idcard';
                }else {
                    return 'text';
                }
            },
            cRadioStyle() {
                let style = `background-color:${this.data.bg_color};width:100%;padding: 16rpx ${+this.data.inputPadding}rpx;`;
                return style;
            },
            cTitleStyle() {
                let style = `color:${this.data.title_color};`;
                if(this.data.style == 3) {
                    style += `left:${+this.data.inputPadding}rpx;`
                    if(this.mode == 'input') {
                        style += `line-height: 1;`
                    }
                }
                return style;
            },
            inputItemStyle() {
                let style = `border-radius:${this.data.radius}rpx;background-color:${this.data.fill_color};padding-top: 16rpx;padding-bottom: 16rpx;`
                if(this.data.border_color) {
                    style += `border: 2rpx solid ${this.data.border_color};`
                };
                return style;
            },
            inputStyle() {
                let style = `color:${this.data.text_color};width: 100%;`;
                if(this.mode == 'position' && !this.text) {
                    style = `color:${this.data.placeholder_color};`;
                }
                if(this.mode == 'text') {
                    style += `min-height: ${this.data.style != 1 && this.data.height ? this.data.height : 56}rpx;`
                }
                if(this.data.style != 1) {
                    style += `background-color:${this.data.fill_color};border-radius:${this.mode == 'text' && this.data.style == 2 ? 0 : this.data.radius}rpx;`
                }else {
                    style += `background-color:${this.data.bg_color};`
                } 
                if(this.data.border_color && this.data.style == 1) {
                    style += `border: 2rpx solid ${this.data.bg_color};border-bottom: 2rpx solid ${this.data.border_color};` 
                }
                if(this.data.style == 3 && this.mode != 'text') {
                    style += `padding-left: 160rpx;text-align: right;`
                }
                return style;
            },
            placeholderStyle() {
                let style = `color:${this.data.placeholder_color};`;
                return style;
            },
            itemStyle() {
                let style = ``;
                let padding = (this.data.style == 3 && this.mode == 'text') ? 12 : 6;
                if((this.data.style == 3 && this.mode == 'text') || (this.data.style != 1 && this.mode != 'text')) {
                    style += `background-color:${this.data.fill_color};border-radius:${this.data.radius}rpx;padding: ${padding}rpx 0;`
                    if(this.data.border_color) {
                        style += `border: 2rpx solid ${this.data.border_color};`
                    }
                }
                return style;
            }
        },
        created() {
            this.data = this.value;
            this.max = this.data.max*10;
            if(this.data.default) {
                this.text = this.data.default;
                this.number = 0;
                for(let item of this.text) {
                    this.number++;
                }
                let value = this.text;
                if(this.mode == 'input') {
                    value = {
                        text: this.text,
                        type: this.data.mode
                    }
                    if(this.data.mode == 1) {
                        value.allow = this.data.allow;
                    }
                }
                this.$emit('updateValue', {
                    index: this.index,
                    value: value,
                });
            }
        },
        methods: {
            getIndex() {
                this.$storage.setStorageSync('input', this.index)
            },
            cancelIndex() {
                this.checkInput(this.text);
                this.$storage.removeStorageSync('input');
            },
            cancelFocus() {
                let index = this.$storage.getStorageSync('index')
                if(index != this.index) {
                    uni.hideKeyboard();
                }
                console.log(index,this.index)
            },
            async getChooseLocation() {
                const self = this;
                if(self.mode != 'position') {
                    return false
                }
                const [err, res] = await uni.chooseLocation();

                if (res) {
                    if(res.name == '我的位置' || res.address == '我的位置' || res.address == '') {
                        uni.showToast({
                            title: '请选择具体位置',
                            icon: 'none'
                        });
                        return false;
                    } 
                    let province = '';
                    let city = '';
                    let area = '';
                    let name = res.name;
                    // #ifdef MP-ALIPAY
                    if(res.provinceName == '上海') {
                        res.provinceName = '上海市'
                    }
                    if(res.provinceName == '澳门特别行政区' || res.provinceName == '香港特别行政区' || res.provinceName == '台湾省') {
                        uni.showToast({
                            title: '不支持该地区',
                            icon: 'none'
                        });
                        return false;
                    }
                    res.address = res.address.replace(res.provinceName,'');
                    res.address = res.address.replace(res.cityName,'');
                    res.address = res.address.replace(res.adName,'');
                    name = res.name ? res.name : res.address;
                    res.address = res.provinceName + res.cityName + res.adName + name;
                    if(!(res.adCode > 0)) {
                        res.address = '其他其他其他'
                    }
                    // #endif
                    if(!res.address) {
                        res.address = '其他其他其他'
                    }
                    res.address = res.address.replace('北京市北京市','北京市');
                    res.address = res.address.replace('天津市天津市','天津市');
                    res.address = res.address.replace('上海市上海市','上海市');
                    res.address = res.address.replace('重庆市重庆市','重庆市');
                    res.address = res.address.replace('香港特别行政区香港特别行政区','香港特别行政区');
                    res.address = res.address.replace('澳门特别行政区澳门特别行政区','澳门特别行政区');
                    if(province == city) {
                        self.text = province + ' ' + area + ' ' + name;
                    }else {
                        self.text = province + ' ' + city + ' ' + area + ' ' + name;
                    }
                    self.$emit('updateValue', {
                        index: self.index,
                        value: self.text,
                    });
                }
                if (err) {
                    const setting = () => {
                        uni.showModal({
                            title: '授权权限',
                            content: '请先授权地理位置权限',
                            success(res) {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success(settingdata) {
                                            if (settingdata.authSetting['scope.userLocation']) {
                                                uni.chooseLocation({
                                                    success: function (res) {
                                                        self.getChooseLocation();
                                                    },
                                                });
                                            } else {
                                                uni.showToast({
                                                    title: '授权失败',
                                                    icon: 'none'
                                                });
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    };

                    //#ifdef MP-BAIDU
                    if (err.errCode === 1003) {
                        setting();
                    }
                    //#endif

                    //#ifdef MP-WEIXIN
                    if (err.errMsg === `chooseLocation:fail auth deny`) {
                        setting();
                    }
                    //#endif
                }
            },
            isEmojiCharacter(substring) {
                for ( var i = 0; i < substring.length; i++) {
                    var hs = substring.charCodeAt(i);
                    if (0xd800 <= hs && hs <= 0xdbff) {
                        if (substring.length > 1) {
                            var ls = substring.charCodeAt(i + 1);
                            var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                            if (0x1d000 <= uc && uc <= 0x1f77f) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    } else if (substring.length > 1) {
                        var ls = substring.charCodeAt(i + 1);
                        if (ls == 0x20e3) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        if (0x2100 <= hs && hs <= 0x27ff) {
                            return true;
                        } else if (0x2B05 <= hs && hs <= 0x2b07) {
                            return true;
                        } else if (0x2934 <= hs && hs <= 0x2935) {
                            return true;
                        } else if (0x3297 <= hs && hs <= 0x3299) {
                            return true;
                        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
            },
            checkInput(value) {
                this.max = this.data.max*10;
                this.number = 0;
                let emoji = 0;
                let is_emoji = false;
                for(let item of value) {
                    this.number++;
                    is_emoji = this.isEmojiCharacter(item)
                    if(this.isEmojiCharacter(item)) {
                        emoji++;
                    }
                }
                if(this.number == this.data.max || this.number > this.data.max) {
                    if(is_emoji) {
                        this.max = e.detail.value.length
                    }else {
                        this.max = +this.data.max + +emoji;
                    }
                }
                let text = value.toString();
                this.text = text;
                let para = {
                    text: this.text,
                    type: this.data.mode
                }
                if(this.data.mode == 1) {
                    para.allow = this.data.allow;
                }
                this.$emit('updateValue', {
                    index: this.index,
                    value: para,
                });
                return text;
            },
            textInput() {
                let value = this.text;
                this.max = this.data.max*10;
                this.number = 0;
                let emoji = 0;
                let is_emoji = false;
                for(let item of value) {
                    this.number++;
                    is_emoji = this.isEmojiCharacter(item)
                    if(this.isEmojiCharacter(item)) {
                        emoji++;
                    }
                }
                if(this.number == this.data.max || this.number > this.data.max) {
                    if(is_emoji) {
                        this.max = value.length;
                    }else {
                        this.max = +this.data.max + +emoji;
                    }
                    this.number = this.data.max;
                }
                this.$emit('updateValue', {
                    index: this.index,
                    value: this.text,
                });
            }
        }
    }
</script>

<style scoped lang="scss">
    .diy-form-input {
        font-size: 30rpx;
        position: relative;
        .diy-form-label {
            flex-shrink: 0;
            margin: 0 20rpx 16rpx 0;
            font-size: 30rpx;
            &.inline {
                position: absolute;
                max-width: 160rpx;
                top: 0;
                height: 100%;
                left: 0;
                white-space: nowrap;
                overflow: hidden;
                z-index: 10;
                font-size: 30rpx;
                padding: 32rpx 20rpx;
                margin: 0;
                >view {
                    padding-left: 0;
                    width: 100%;
                    >view {
                        width: 100%;
                        overflow: hidden;
                    }
                }
            }
            >view {
                position: relative;
                display: inline-block;
                padding-left: 24rpx;
                text {
                    color: #FF4544;
                    position: absolute;
                    right: -16rpx;
                    top: 0;
                }
            }
        }
        .input-item {
            position: relative;
            .count-num {
                position: absolute;
                font-size: 28rpx;
                color: #BEC3C7;
                display: inline-block;
                right: 11rpx;
                bottom: 10rpx;
                &.bottom {
                    bottom: 16rpx;
                }
            }
            input {
                padding: 0 24rpx;
                font-size: 30rpx;
                height: 72rpx;
            }
            .position {
                padding: 14rpx 68rpx 14rpx 24rpx;
                font-size: 30rpx;
                position: relative;
                min-height: 70rpx;
                .position-icon {
                    width: 40rpx;
                    height: 40rpx;
                    position: absolute;
                    top: 15rpx;
                    right: 14rpx;
                }
            }
            textarea {
                width: 100%;
                padding: 0 20rpx;
                height: auto;
            }
        }
    }
</style>
